<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.2/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"littlefxc.github.io","root":"/","images":"/images","scheme":"Mist","version":"8.2.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}};
  </script>
<meta name="description" content="Ribbon负载均衡的原理是:从EurekaClient类的Bean获取Provider提供者服务列表清单，并且定 期通过IPing类的Bean去判断Provider的可用性。每次RPC到来时，在Provider提供者服务列表中根据 IRule策略类的Bean计算出每次RPC要访问的最终Provider。">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring Cloud Ribbon 的负载均衡策略">
<meta property="og:url" content="http://littlefxc.github.io/2021/09/28/Spring-Cloud-Ribbon-%E7%9A%84%E8%B4%9F%E8%BD%BD%E5%9D%87%E8%A1%A1%E7%AD%96%E7%95%A5/index.html">
<meta property="og:site_name" content="一年春又来">
<meta property="og:description" content="Ribbon负载均衡的原理是:从EurekaClient类的Bean获取Provider提供者服务列表清单，并且定 期通过IPing类的Bean去判断Provider的可用性。每次RPC到来时，在Provider提供者服务列表中根据 IRule策略类的Bean计算出每次RPC要访问的最终Provider。">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-09-28T03:10:17.000Z">
<meta property="article:modified_time" content="2021-09-28T03:26:05.047Z">
<meta property="article:author" content="一年春又来">
<meta property="article:tag" content="负载均衡">
<meta property="article:tag" content="ribbon">
<meta property="article:tag" content="java">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="http://littlefxc.github.io/2021/09/28/Spring-Cloud-Ribbon-%E7%9A%84%E8%B4%9F%E8%BD%BD%E5%9D%87%E8%A1%A1%E7%AD%96%E7%95%A5/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>
<title>Spring Cloud Ribbon 的负载均衡策略 | 一年春又来</title>
  




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="一年春又来" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">一年春又来</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home"><a href="/" rel="section"><i class="home                          //首页 fa-fw"></i>首页</a></li>
        <li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="archive          //归档 fa-fw"></i>归档</a></li>
        <li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="th           //分类 fa-fw"></i>分类</a></li>
        <li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="tags                     //标签 fa-fw"></i>标签</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-overview-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">一年春又来</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">234</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">38</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">125</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://littlefxc.github.io/2021/09/28/Spring-Cloud-Ribbon-%E7%9A%84%E8%B4%9F%E8%BD%BD%E5%9D%87%E8%A1%A1%E7%AD%96%E7%95%A5/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="一年春又来">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="一年春又来">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Spring Cloud Ribbon 的负载均衡策略
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>
      

      <time title="创建时间：2021-09-28 11:10:17 / 修改时间：11:26:05" itemprop="dateCreated datePublished" datetime="2021-09-28T11:10:17+08:00">2021-09-28</time>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <p>Ribbon负载均衡的原理是:从EurekaClient类的Bean获取Provider提供者服务列表清单，并且定 期通过IPing类的Bean去判断Provider的可用性。每次RPC到来时，在Provider提供者服务列表中根据 IRule策略类的Bean计算出每次RPC要访问的最终Provider。</p>
<span id="more"></span>

<p>Ribbon内部有一个负载均衡器接口<code>ILoadBalance</code>，定义了添加Provider、获取所有的Provider列表、 获取可用的Provider列表等基础的操作。该接口的核心实现类<code>DynamicServerListLoadBalancer</code>会通过 EurekaClient(实现类为DiscoveryClient)获取Provider清单，并且通过<code>IPing</code>实例定期(每10s)向每 个Provider实例发送“ping”，并且根据Provider是否有响应来判断该Provider提供者实例是否可用。 如果该Provider的可用性发生了改变，或者Provider清单中的数量和之前的不一致，则从注册中心更新或者重新拉取Provider服务实例清单。</p>
<p>每次RPC请求到来时，由Ribbon的IRule负载均衡策略接口的某个实现类就来进行负载均衡。主要的负载均衡的策略实现类如下:</p>
<ol>
<li><p>随机策略(RandomRule) </p>
<p>该策略实现类从Provider提供者服务列表中随机选择一个Provider服务实例，作为RPC请求的目标Provider。</p>
</li>
<li><p>线性轮询策略(RoundRobinRule)</p>
<p>RoundRobinRule线性轮询和RandomRule相似，只是每次都取下一个Provider服务器。假设一共有5台Provider服务节点，使用线性轮询策略，第1次取第1台，第2次取第2台，第3次取第3台，以此类推。</p>
</li>
<li><p>响应时间权重策略(WeightedResponseTimeRule)</p>
<p>WeightedResponseTimeRule策略为每一个Provider服务维护一个权重值，其规则简单概况为 Provider服务响应时间越长，其权重就越小。在进行服务器选择时，权重值越小，被选择的机会越少。 WeightedResponseTimeRule继承了RoundRobinRule，开始时每一个Provider都没有权重值，每当RPC 请求过来时，由其父类的轮询算法完成负载均衡方式。该策略类有一个默认、每30秒执行一次的权 重更新定时任务，该定时任务会根据Provider实例的响应时间更新Provider权重列表。后续有RPC过来时，将根据权重值进行负载均衡。</p>
</li>
<li><p>最少连接策略(BestAvailableRule)</p>
<p>在进行服务器选择时，该策略类遍历Provider清单，选取出可用的且连接数最少的一个Provider。 该策略类里面有一个LoadBalancerStats类型的成员变量，会存储所有Provider的运行状况和连接数。 在进行负载均衡计算时，如果选取到的Provider为null，那么会调用线性轮询策略重新选取。</p>
</li>
<li><p>重试策略(RetryRule)</p>
<p>该类会在一定的时限内进行Provider循环重试。RetryRule会在每次选取之后，对选举的Provider进行判断，如果为null或者not alive，会在一定的时限内(如500ms)内会不停的选取和判断。</p>
</li>
<li><p>可用过滤策略(AvailabilityFilteringRule)</p>
<p>该类扩展了线性轮询策略，会先通过默认的线性轮询策略选取一个Provider，再去判断该Provider 是否超时可用，当前连接数是否超过限制，如果都满足要求，则成功返回。</p>
<p>简单来说，AvailabilityFilteringRule将对候选的Provider进行可用性过滤，会先过滤掉多次访问 故障而处于断路器跳闸状态的Provider服务，还会过滤掉并发的连接数超过阈值的Provider服务，然后，对剩余的服务列表进行线性轮询。</p>
</li>
<li><p>区域过滤策略(ZoneAvoidanceRule)</p>
<p>该类扩展了线性轮询策略，除了过滤超时和连接数过多的Provider之外，还会过滤掉不符合要求的Zone区域中的所有节点。</p>
</li>
</ol>
<p>Ribbon实现的负载均衡策略，不止以上7种，还可以实现自定义的策略类。</p>
<p>局部微服务负载均衡配置示例如下：</p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">user-provider:</span></span><br><span class="line">  <span class="attr">ribbon:</span></span><br><span class="line">    <span class="attr">NFLoadBalancerRuleClassName:</span> <span class="string">com.netflix.loadbalancer.RetryRule</span> <span class="comment">#重试+线性轮询</span></span><br><span class="line">  <span class="comment"># NFLoadBalancerRuleClassName: com.netflix.loadbalancer.BestAvailableRule #最少连接策略</span></span><br><span class="line">  <span class="comment"># NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule #随机选择</span></span><br></pre></td></tr></table></figure>

<p>如果要配置全局的、针对所有的Provider都使用的负载均衡策略，可以在配置文件中直接使用 <code>ribbon.NFLoadBalancerRuleClassName</code>配置项进行配置，具体如下:</p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">ribbon:</span></span><br><span class="line">  <span class="attr">NFLoadBalancerRuleClassName:</span> <span class="string">com.netflix.loadbalancer.RetryRule</span> <span class="comment">#重试+线性轮询</span></span><br><span class="line"><span class="comment"># NFLoadBalancerRuleClassName: com.netflix.loadbalancer.BestAvailableRule #最少连接策略</span></span><br><span class="line"><span class="comment"># NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule #随机选择</span></span><br></pre></td></tr></table></figure>


    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/%E8%B4%9F%E8%BD%BD%E5%9D%87%E8%A1%A1/" rel="tag"># 负载均衡</a>
              <a href="/tags/ribbon/" rel="tag"># ribbon</a>
              <a href="/tags/java/" rel="tag"># java</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2021/09/27/Mycat-%E5%88%86%E7%89%87%E8%A7%84%E5%88%99/" rel="prev" title="Mycat 分片规则">
                  <i class="fa fa-chevron-left"></i> Mycat 分片规则
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2021/10/19/%E7%BD%91%E7%BB%9C%E5%9F%BA%E7%A1%80%E6%A6%82%E8%BF%B0/" rel="next" title="网络基础概述">
                  网络基础概述 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>







<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">一年春又来</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/mist/" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  
<script src="/js/local-search.js"></script>






  





</body>
</html>
